from flask import Flask, request, jsonify
import json
import picologging as logging
logging.basicConfig()

import message
import utils
from datetime import datetime


message_queue = utils.init_message_queue()
# set reload message_queue time (minutes)
isReloadTime = utils.reload_message_queue_timer(15)
logger = logging.getLogger("app")
app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False

@app.route("/api/message_queue_enqueue", methods=["GET", "POST"])
def message_queue_enqueue():
    data_file = "data.json"

    logger.info("message_queue_enqueue")
    if not request.data:
        print("no data")
    data = request.data.decode("utf-8")
    logger.info("data is :", data)
    data_json = json.loads(data)
    current_time = datetime.now().strftime("%H:%M:%S")
    logger.info("message data is :", data_json)
    temp_message = message.Message(data=data_json['data'], time=current_time)
    logger.info("message data is :", temp_message.to_json())
    utils.message_queue_enqueue(message_queue=message_queue,new_message=temp_message)
    logger.info('write file')
    utils.write_to_file(filename=data_file,data=message_queue.to_json())
    # reload message_queue erver 15 minutes
    if isReloadTime():
        print("reload time")
        utils.init_message_queue()
    # new_message_data,new_message_time = utils.get_last_message(message_queue)
    return jsonify({"code": 200, "msg": "success", "data": {'data':temp_message.get_data(),'time':temp_message.get_time()}})

@app.route("/api/message_latest_message", methods=["GET", "POST"])
def get_message_queue():
    logger.info("message_latest_message")
    if not request.data:
        print("no data")
    data = request.data.decode("utf-8")
    logger.info("data is :", data)
    data_json = json.loads(data)
    logger.info("message data is :", data_json)
    print("message data is :",data_json)
    request_len = int(data_json['data'])
    print("request_len is :",request_len)
    message_json = utils.get_messages(message_queue,request_len)
    
    if request_len == 1 or request_len < 1:
        request_len = 1
        message_json = utils.get_last_message(message_queue)
    logger.info('write file')
    
    # reload message_queue erver 15 minutes
    if isReloadTime():
        print("reload time")
        utils.init_message_queue()
    return jsonify({"code": 200, "msg": "success", "data": message_json})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9090, debug=True)
